package io.gitee.minelx.filesystem;

import io.gitee.minelx.filesystem.init.OpenPolicy;
import io.gitee.minelx.filesystem.provider.FS;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import static io.gitee.minelx.filesystem.init.OpenPolicy.*;

public class TempPath implements AutoCloseable {

	private static final Directory TEMP_FILES_DIRECTORY = FS.workingDir()
			.child().dir("temp_files", OpenPolicy.CREATE_IF_NOT_EXISTED);

	private final Path path;

	private TempPath(Path path) {
		this.path = path;
	}

	public File file() {
		return file(OpenPolicy.CREATE_IF_NOT_EXISTED);
	}

	public Directory dir() {
		return dir(OpenPolicy.CREATE_IF_NOT_EXISTED);
	}

	public File file(OpenPolicy openPolicy) {
		return File.create(path, openPolicy);
	}

	public Directory dir(OpenPolicy openPolicy) {
		return Directory.create(path, openPolicy);
	}

	@Override
	public void close() {
		path.deleteIfExists();
	}

	public static TempPath of(String fileName) {
		return of(tempFileDirectoryAtWorkingDir(), fileName);
	}

	public static TempPath random() {
		return random(tempFileDirectoryAtWorkingDir());
	}

	public static TempPath random(String content) {
		return random(tempFileDirectoryAtWorkingDir(), content);
	}

	public static TempPath of(Directory tempFilesDirectory, String fileName) {
		Path path = tempFilesDirectory.child().path(fileName);
		return new TempPath(path);
	}

	public static TempPath random(Directory tempFilesDirectory) {
		return of(tempFilesDirectory, UUID.randomUUID().toString());
	}

	public static TempPath random(Directory tempFilesDirectory, String content) {
		try {
			TempPath result = random(tempFilesDirectory);
			result.file().write(content, StandardCharsets.UTF_8);
			return result;
		} catch (IOException e) {
			throw new RuntimeException("error while writing content to random file.", e);
		}
	}

	public static Directory tempFileDirectoryAtWorkingDir() {
		return TEMP_FILES_DIRECTORY;
	}
}